<template>
  <ych-modal
    :fullscreen="true"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :closable="false"
    :footer="null">
    <a-spin :spinning="confirmLoading">
      <div class="report-designer-toolbar">
        <span class="report-designer-title">{{title}}</span>
        <div class="report-designer-button-group">
          <a-popconfirm placement="bottomRight" :title="$t('m.common.tip.save_confirm')" @confirm="() => handleOk()">
            <a-button icon="save" type="primary">{{ $t('m.common.button.save') }}</a-button>
          </a-popconfirm>
          <a-button icon="reload" @click="createChartData">{{ $t('m.common.button.refresh') }}</a-button>
          <a-button icon="table" @click="showDataTable">{{$t('m.eform.appreport.other.viewData')}}</a-button>
          <a-button icon="credit-card" @click="handleOpenJsonModal">{{$t('m.eform.appreport.other.generateJSON')}}</a-button>
          <a-button icon="delete" @click="handleReset">{{ $t('m.common.button.clear') }}</a-button>
          <a-button type="link" icon="close" @click="handleCancel"></a-button>
        </div>
      </div>
      <a-form :form="form">
        <a-row>
          <a-col :span="7">
            <a-form-item :label="$t('m.eform.appreport.entity.widgetName') " :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-top: 12px;">
              <a-input v-decorator="[ 'widgetName', validatorRules.widgetName]" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item :label="$t('m.eform.appreport.entity.widgetCode') " :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-top: 12px;">
              <a-input v-decorator="[ 'widgetCode', validatorRules.widgetCode]" placeholder=""></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item :label="$t('m.eform.appreport.entity.datasetId')" :labelCol="labelCol" :wrapperCol="wrapperCol" style="margin-top: 12px;">
              <report-dataset-tag v-model="datasetId" placeholder="" :groupId="groupId"></report-dataset-tag>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item :label="$t('m.common.label.sort')" :labelCol="labelCol2" :wrapperCol="wrapperCol2" style="margin-top: 12px;">
              <a-input-number v-decorator="[ 'orderNum', validatorRules.orderNum]"></a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <widget-design ref="designer" :datasetId="datasetId" :initConfig="initConfig" :height="height"
                           :expressions="expressions" :filterGroups="filterGroups" :groupId="groupId"></widget-design>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </ych-modal>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import ReportDatasetTag from '../../eform/select/tag/ReportDatasetTag'
  import { WidgetDesign } from './widgetDesigner/packages'
  import YchConstant from "@/api/YchConstant";

  export default {
    name: 'ActReportWidgetModal',
    components: {
      ReportDatasetTag,
      WidgetDesign
    },
    props: {
      groupId: {
        type: String,
        required: true
      },
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title: this.$t('m.eform.formDesign.label.bao-biao-she-ji'),
        visible: false,
        model: {},
        bodyStyle: {
          padding: 0,
          margin: 0
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: {span: 24},
          sm: {span: 12}
        },
        wrapperCol2: {
          xs: {span: 24},
          sm: {span: 12}
        },
        confirmLoading: false,
        validatorRules: {
          widgetName: { rules: [{ required: true, message: this.$t('m.eform.appreport.verify.widgetName') }] },
          widgetCode: { rules: [{ required: true, message: this.$t('m.eform.appreport.verify.widgetCode') }, { validator: this.checkCode }] },
          orderNum: {
            initialValue: 1 // TODO 默认值取数据库最大值+10
          },
        },
        url: {
          add: YchConstant.PREFIX_EFORM + '/report/actReportWidget/add',
          edit: YchConstant.PREFIX_EFORM + '/report/actReportWidget/edit',
          checkCode: YchConstant.PREFIX_EFORM + '/report/actReportWidget/checkCode',
        },
        height: document.body.clientHeight - 52 - 66 - 12 + 'px',
        datasetId: null,
        initConfig: {},
        expressions: [],
        filterGroups: []
      }
    },
    methods: {
      initDataJson () {
        const dataJson = JSON.parse(this.model.dataJson || '{}')
        this.datasetId = dataJson.datasetId || null
        this.initConfig = dataJson.config || {}
        this.expressions = dataJson.expressions || []
        this.filterGroups = dataJson.filterGroups || []
      },
      add () {
        this.edit({})
      },
      edit (record) {
        this.title = record.widgetName || this.$t('m.eform.formDesign.label.bao-biao-she-ji')
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.initDataJson()
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(this.lodash.pick(this.model, 'widgetName', 'widgetCode', 'orderNum'))
        })
      },
      close () {
        this.$emit('close')
        this.visible = false
        this.initConfig = {}
        this.$refs.designer.close()
      },
      handleOk () {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            formData.groupId = this.groupId
            that.$refs.designer.createDataJson().then((dataJson) => {
              formData.dataJson = JSON.stringify(dataJson)
              httpAction(httpurl, formData, method).then((res) => {
                if (res.success) {
                  that.messageUtil.success(res.message)
                  that.$emit('ok')
                } else {
                  that.messageUtil.warning(res.message)
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            }).catch((error) => {
              that.messageUtil.warning(error)
              that.confirmLoading = false
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      createChartData () {
        this.$refs.designer.createChartData()
      },
      showDataTable () {
        this.$refs.designer.showDataTable()
      },
      handleOpenJsonModal () {
        this.$refs.designer.handleOpenJsonModal()
      },
      handleReset () {
        this.$refs.designer.handleReset()
      },
      checkCode (rule, value, callback) {
        if (!value) {
          callback()
          return
        }
        let reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
        if(reg.test(value)){
          callback(this.$t('m.eform.appreport.verify.widgetCode_format'))
          return
        }
        getAction(this.url.checkCode, {
          value: value,
          id: this.model.id
        }).then((res) => {
          res.success ? callback() : callback(res.message)
        })
      }
    }
  }
</script>
<style scoped lang="less">
  .report-designer-toolbar {
    width: 100%;
    height: 50px;
    line-height: 50px;
    padding: 0px 10px 0px 10px;
    background: #fff;
    border-bottom: 1px solid #e8e8e8;

    .report-designer-title {
      height: 50px;
      line-height: 50px;
      font-size: 18px;
      font-weight: 600;
      margin: 0px 0px 0px 10px;
      display: inline-block;
    }

    .report-designer-button-group {
      display: inline-block;
      float: right;

      .ant-btn {
        margin: 6px 6px;
      }
    }
  }
</style>
